package config

import (
	"github.com/spf13/viper"
	"log"
	"os"
	"path/filepath"
)

type DbInfo struct {
	Dsn    string
	Enable bool
}

type CronTaskInfo struct {
	Name     string
	CronSpec string
	Enable   bool
	Note     string
}

type MediaInfo struct {
	AppId     int
	AppSecret string
}

type Config struct {
	App struct {
		Name string
		Port string
	}
	Media struct {
		Ocean   MediaInfo
		OceanQC MediaInfo
	}
	Database struct {
		Cid     DbInfo
		Sucai   DbInfo
		SucaiTk DbInfo `yaml:"sucaiTk"` // tiktok素材系统的数据库
	}
	Redis struct {
		Addr   string
		Enable bool
	}
	CronJob struct {
		On    bool
		Tasks []CronTaskInfo
	}

	RabbitMQ RabbitMQConfig `yaml:"rabbitmq"`
}

type RabbitMQConfig struct {
	URL        string `yaml:"url"`
	BatchQueue string `yaml:"batch_queue"`
}

var AppConfig *Config

func InitConfig() {
	viper.SetConfigName("config")
	viper.SetConfigType("yml")
	// 获取当前工作目录的绝对路径
	wd, err := os.Getwd()
	if err != nil {
		log.Fatalf("获取当前工作目录失败: %v", err)
	}

	// 设置配置路径为当前路径的绝对路径
	viper.AddConfigPath(filepath.Join(wd, "config"))
	if err := viper.ReadInConfig(); err != nil {
		log.Fatalf("Error reading config file: %v", err)
	}

	AppConfig = &Config{}

	if err := viper.Unmarshal(AppConfig); err != nil {
		log.Fatalf("Unable to decode into struct: %v", err)
	}

	InitDB()
	if AppConfig.Redis.Enable {
		InitRedis()
	}
}
